package com.king.shiro;


import com.king.pojo.User;
import com.king.service.UserService;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

/**
 * @author King_long
 * @program: learn_platform
 * @Date 2020/01/02 15:27
 */
@Component("myRealm")
public class MyRealm extends AuthorizingRealm {

    private static final Logger LOGGER = LogManager.getLogger(MyRealm.class);

    @Autowired
    private UserService userService;

    /**
     * 授权
     *
     * @param principals
     * @return
     */
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {

        SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();

        String username = getAuthorizationCacheKey(principals).toString();

        LOGGER.info("====AuthorizationInfo===" + username);

        return null;
    }

    /**
     * 认证
     *
     * @param token
     * @return
     * @throws AuthenticationException
     */
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {

        SimpleAuthenticationInfo info = null;

        UsernamePasswordToken token1 = (UsernamePasswordToken) token;

        String username = token1.getUsername();

        String password = new String(token1.getPassword());

        LOGGER.info("====AuthenticationInfo====" + username + "=====" + password);

        User user = userService.login(username, password);


        if (user != null && user.getId() != 0) {


            info = new SimpleAuthenticationInfo(username, password, getName());
        }

        return info;
    }
}
